/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gtugs.service;

import org.gtugs.domain.Chapter;
import org.gtugs.domain.Point;
import org.gtugs.domain.User;
import org.springframework.validation.Validator;
import org.springframework.validation.Errors;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author jasonacooper@google.com (Jason Cooper)
 */
public class ChapterValidator implements Validator {

  private MapsService mapsService;

  public boolean supports(Class c) {
    return Chapter.class.equals(c);
  }

  public void validate(Object obj, Errors errors) {
    Chapter chapter = (Chapter) obj;
    boolean locationErrors = false;

    if (chapter == null) {
      errors.rejectValue("name", null, null, "Name required");
    }
    else {
      if (chapter.getName() == null || chapter.getName().equals("")) {
        errors.rejectValue("name", null, null, "Name required");
      }
      if (chapter.getType() == null || chapter.getType().equals("")) {
        errors.rejectValue("type", null, null, "Type required");
      }
      /*if ((chapter.getCity() == null || chapter.getCity().equals("")) &&
          (chapter.getState() == null || chapter.getState().equals(""))) {
        errors.rejectValue("city", null, null, "City and/or state required");
        errors.rejectValue("state", null, null, "City and/or state required");
        locationErrors = true;
      }*/
      if (chapter.getCountry() == null || chapter.getCountry().equals("")) {
        errors.rejectValue("country", null, null, "Country required");
        locationErrors = true;
      }
      if (chapter.getStatus() == null || chapter.getStatus().equals("")) {
        errors.rejectValue("status", null, null, "Status required");
      }

      if (!locationErrors) {
        Point point = mapsService.getCoordinates(chapter.getCity(),
            chapter.getState(), chapter.getCountry());
        if (point == null) {
          errors.rejectValue("city", null, null, "Geocoding failed: given address may be invalid or geocoding service may be offline");
          errors.rejectValue("state", null, null, "Geocoding failed: given address may be invalid or geocoding service may be offline");
          errors.rejectValue("country", null, null, "Geocoding failed: given address may be invalid or geocoding service may be offline");
        } else {
          chapter.setLatitude(point.getLatitude());
          chapter.setLongitude(point.getLongitude());
        }
      }

      if ((chapter.getWebsite() == null || chapter.getWebsite().equals("")) &&
          (chapter.getMailingList() == null ||
          chapter.getMailingList().equals(""))) {
        errors.rejectValue("website", null, null,
            "Website and/or mailing list required");
        errors.rejectValue("mailingList", null, null,
            "Website and/or mailing list required");
      }
      if (chapter.getWebsite() != null &&
          !chapter.getWebsite().equals("")) {
        if (!isValidUrl(chapter.getWebsite())) {
          errors.rejectValue("website", null, null, "Invalid website");
        }
      }
      if (chapter.getMailingList() != null &&
          !chapter.getMailingList().equals("")) {
        if (!isValidUrl(chapter.getMailingList())) {
          errors.rejectValue("mailingList", null, null,
              "Invalid mailing list");
        }
      }

      for (int i = 0; i < chapter.getAdministrators().size(); i++) {
        User u = chapter.getAdministrators().get(i);

        if (u.getName() == null || u.getName().equals("")) {
          errors.rejectValue("administrators[" + i + "].name", null, null,
              "Name required");
        }
        if (u.getEmail() == null || u.getEmail().equals("")) {
          errors.rejectValue("administrators[" + i + "].email", null, null,
              "Email required");
        } else if (!isValidEmail(u.getEmail())) {
          errors.rejectValue("administrators[" + i + "].email", null, null,
              "Invalid email");
        }
      }
    }
  }

  private boolean isValidEmail(String email) {
    // From http://regexlib.com/DisplayPatterns.aspx
    String regex = "^([0-9a-zA-Z]([-.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]" +
        "*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";

    return email.matches(regex);
  }

  private boolean isValidUrl(String urlString) {
    try {
      URL url = new URL(urlString);
    } catch (MalformedURLException e) {
      return false;
    }

    return true;
  }

  public void setMapsService(MapsService mapsService) {
    this.mapsService = mapsService;
  }
}
